package studiodiva.portfolio.client.lib.collections;

import java.util.List;
import java.util.Map;

import static studiodiva.portfolio.client.lib.lang.Lang.list;

public class MapIterator<K, V> extends GenericIterator<Mapped<K, V>> implements Mapped<K, V> {

  private final List<K> keys;
  private int last_index = -1;
  private final Map<K, V> map;

  public MapIterator(Map<K, V> map) {
    super(map.size());
    this.map = map;
    this.keys = list(map.keySet());
  }

  public MapItem<K, V> get() {
    if (last_index != getIndex()) last_index = getIndex();
    return this;
  }

  public MapItem<K, V> getNext() {
    return getItem(getIndex() + 1);
  }

  public MapItem<K, V> getPrevious() {
    return getItem(getIndex() - 1);
  }

  public K key() {
    return keys.get(getIndex());
  }

  @Override
  public void onRemove() {
    removeItem(getIndex());
    last_index = -1;
  }

  public V value() {
    return map.get(key());
  }

  protected MapItem<K, V> getItem(int index) {
    return new MapItemImpl<K, V>(map, keys.get(index));
  }

  @Override
  protected Mapped<K, V> getValue() {
    return this;
  }

  protected void removeItem(int index) {
    map.remove(keys.get(index));
    keys.remove(index);
  }
}
